package com.example.petchating.UI

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.*
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
import com.example.petchating.entities.Pet
import com.example.petchating.network.ChatHistoryRepository
import com.example.petchating.network.ChatService
import com.example.petchating.network.EmotionService

class ChatDialog(
    private val stage: Stage,
    private val pet: Pet,
    private val chatService: ChatService,
    private val historyRepo: ChatHistoryRepository,
    private val emotionService: EmotionService,
    skin: Skin
) : Window("Dr. Pet", skin) {

    private val messageLabel: Label = Label("你好", Label.LabelStyle(skin.getFont("chinese-font"), Color.WHITE))
    private val inputField: TextField
    private val sendButton: TextButton
    private val closeButton: TextButton

    init {

        // 加载历史
        val history = historyRepo.getHistory()
        if (history.isNotEmpty()) {
            val (lastMessage, lastReply) = history.last()
            messageLabel.setText("你上次问的是：$lastMessage\npet回复：$lastReply")
        }

        isMovable = false
        isModal = true
        isVisible = false


        // 取出中文字体
        val chineseFont = skin.getFont("chinese-font")
        chineseFont.data.setScale(2f)

        // 设置背景
        val backgroundDrawable = skin.getDrawable("default-round") ?: skin.getDrawable("default-window")
        background = backgroundDrawable

        // 自定义样式
        val labelStyle = Label.LabelStyle(chineseFont, Color.WHITE)
        val textFieldStyle = skin.get(TextField.TextFieldStyle::class.java).also {
            it.font = chineseFont
        }
        val buttonStyle = TextButton.TextButtonStyle().apply {
            font = chineseFont
            fontColor = Color.WHITE
            up = skin.getDrawable("default-round")
            down = skin.getDrawable("default-round-down")
        }

        // 初始化组件，使用自定义字体样式
//        messageLabel = Label("你好", labelStyle)
        // ✅ 显示历史记录（只显示最后一条，也可以全部展示）

        inputField = TextField("", textFieldStyle)
        sendButton = TextButton("发送", buttonStyle)
        closeButton = TextButton("关闭", buttonStyle)

        // Label 设置
        messageLabel.setWrap(true)
        messageLabel.setAlignment(Align.topLeft)

        pad(20f)
        add(messageLabel).growX().colspan(2).row()
        add(inputField).growX()
        add(sendButton).width(80f).row()
        add(closeButton).colspan(2).padTop(10f)

        sendButton.addListener(object : ClickListener() {
            override fun clicked(event: InputEvent?, x: Float, y: Float) {
                val userInput = inputField.text.trim()
                if (userInput.isNotBlank()) {
                    inputField.setText("")
                    messageLabel.setText("正在分析情绪...")

                    // 先进行情感分析
                    emotionService.analyzeEmotion(userInput) { emotion ->
                        Gdx.app.postRunnable {
                            messageLabel.setText("检测到的情绪：$emotion\n正在思考回复...")

                            // 更新宠物的心情
                            pet.updateMood(emotion)

                            // 然后进行回复请求
                            chatService.sendMessage(userInput) { reply ->
                                Gdx.app.postRunnable {
                                    val finalReply = "（$emotion）$reply"
                                    messageLabel.setText(finalReply)

                                    // 保存记录
                                    historyRepo.saveChat(userInput, finalReply)
                                }
                            }
                        }
                    }
                }
            }
        })


        closeButton.addListener(object : ClickListener() {
            override fun clicked(event: InputEvent?, x: Float, y: Float) {
                isVisible = false
            }
        })

        pack()
        setSizeBasedOnStage()
    }

    fun setSizeBasedOnStage(widthRatio: Float = 0.8f, heightRatio: Float = 0.2f) {
        val targetWidth = stage.viewport.worldWidth * widthRatio
        val targetHeight = stage.viewport.worldHeight * heightRatio
        setSize(targetWidth, targetHeight)
        centerDialog()
    }

    fun centerDialog() {
        val x = (stage.viewport.worldWidth - width) / 2f
        val y = (stage.viewport.worldHeight - height) / 2f
        val offsetY = -stage.viewport.worldHeight * 0.5f // 向下偏移 10%
        setPosition(x, y + offsetY)
    }
}
